import React, { PureComponent, Fragment } from 'react';
import { connect } from 'react-redux';
import { Switch, Route, withRouter } from 'react-router';
import { Redirect } from 'react-router-dom';
import Loadable from 'react-loadable';

import Loading from '../components/common/lazyLoading';
import { getQueryParam } from '../utils/url';
import withNav from '../components/nav/nav.chongqing';
import GiftModal from '../components//coupon/giftModal';
import {
  COUPON_GIFT_SH,
  COUPON_GIFT_SHELL,
} from '../constants/setting';

export const basePath = '/cq';

export const routes = [
  {
    path: '/agreement',
    needLogin: false,
    component: Loadable({
      loader: () => import('../pages/app/agreement'),
      loading: Loading,
    }),
  },
  {
    path: '/login',
    needLogin: false,
    component: Loadable({
      loader: () => import('../pages/user/login.cq'),
      loading: Loading,
    }),
  },
  {
    path: '/home',
    needLogin: true,
    component: withNav(
      Loadable({
        loader: () => import('../pages/home/home.cq'),
        loading: Loading,
      }),
      0,
    ),
  },
  {
    path: '/refuel',
    needLogin: true,
    component: Loadable({
      loader: () => import('../pages/refuel/refuel.cq'),
      loading: Loading,
    }),
  },
  {
    path: '/giftCenter',
    needLogin: true,
    component: withNav(
      Loadable({
        loader: () => import('../pages/user/giftCenter.cq'),
        loading: Loading,
      }),
      1,
    ),
  },
  {
    path: '/userCenter',
    needLogin: true,
    component: withNav(
      Loadable({
        loader: () => import('../pages/user/userCenter.cq'),
        loading: Loading,
      }),
      2,
    ),
  },
  {
    path: '/result',
    needLogin: true,
    component: Loadable({
      loader: () => import('../pages/result/result'),
      loading: Loading,
    }),
  },
  // {
  //   path: '/moreCoupon',
  //   needLogin: true,
  //   component: Loadable({
  //     loader: () => import('../pages/coupon/moreCoupon'),
  //     loading: Loading,
  //   }),
  // },
  {
    path: '*',
    component: Loadable({
      loader: () => import('../pages/app/404'),
      loading: Loading,
    }),
  },
];

@withRouter
@connect(({ user, coupon, loading }) => {
  return {
    user: user.get('user'),
    showDialog: coupon.getIn(['dialog', 'show']),
    dialogType: coupon.getIn(['dialog', 'type']),
    needCarNo: coupon.getIn(['dialog', 'needCarNo']),
    giftBusy: ['coupon/getGiftPackage'].some(action => loading.effects[action]),
  };
})
class CqRoutes extends PureComponent {
  state = {
    showNav: true,
  }
  componentDidMount() {
    window.source = 'CHONGQINGPUBLIC';
    this.checkSource();
    if (!getQueryParam('yyeCode')) {
      this.fetchCouponDialog();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.user.get('token') && nextProps.user !== this.props.user) {
      setTimeout(() => {
        this.fetchCouponDialog();
      }, 300);
    }
  }

  checkSource = () => {
    const { user } = this.props;
    if (user.get('fromTmall') && !getQueryParam('yyeCode')) {
      window.source = 'TAOBAO';
      // eslint-disable-next-line
      this.setState({
        showNav: false,
      });
    }
  }

  fetchCouponDialog = () => {
    const { user } = this.props;
    if (user.get('token') && window.source !== 'TAOBAO') {
      this.props.dispatch({
        type: 'coupon/fetchShellDialog',
      });
    }
  }

  giftFunc = (type, carNo) => {
    const { needCarNo, giftBusy } = this.props;
    console.log('+++++', giftBusy);
    if (giftBusy) {
      console.log('========');
      return;
    }
    if (type === 'sh') {
      this.props.dispatch({
        type: 'coupon/getGiftPackage',
        payload: {
          markId: COUPON_GIFT_SH,
          carNo: needCarNo ? carNo : null,
        },
      });
    } else {
      this.props.dispatch({
        type: 'coupon/getGiftPackage',
        payload: {
          markId: COUPON_GIFT_SHELL,
          carNo: needCarNo ? carNo : null,
        },
      });
    }
  }

  closeFunc = () => {
    this.props.dispatch({
      type: 'coupon/closeDialog',
    });
  }

  render() {
    const { showNav } = this.state;
    const {
      user,
      needCarNo,
      showDialog,
      dialogType,
    } = this.props;
    const cells = routes.map((route) => {
      const {
        path,
        component: AppComponent,
        needLogin,
        ...rest
      } = route;
      const relPath = `${basePath}${path}`;
      return (
        <Route
          key={relPath}
          path={relPath}
          {...rest}
          render={(props) => { // eslint-disable-line
            if (needLogin && !user.get('token') && !getQueryParam('yyeCode') && path !== '/login') {
              const redirect = {
                pathname: `${basePath}/login`,
                search: `?callbackUrl=${basePath}${path}`,
              };
              return <Redirect to={redirect} />;
            } else {
              return <AppComponent showNav={showNav} {...props} canRefuel />;
            }
          }}
        />
      );
    });
    return (
      <Fragment>
        <Switch>
          {cells}
        </Switch>
        <GiftModal
          giftFunc={this.giftFunc}
          closeFunc={this.closeFunc}
          needCarNo={needCarNo}
          type={dialogType}
          show={showDialog}
        />
      </Fragment>

    );
  }
}

export default CqRoutes;

